import { createRouter, createWebHistory } from 'vue-router'
import { VerifyToken_API } from '@/api/user.js'
import { message } from 'ant-design-vue'

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '',
            component: () => import('@/views/start/index.vue'),
        },
        {
            path: '/in',
            component: () => import('@/views/start/component/SignIn.vue')
        },
        {
            path: '/up',
            component: () => import('@/views/start/component/SignUp.vue')
        },
        {
            path: '/main',
            components: {
                default: () => import('@/views/main/index.vue'),
            },
            children: [
                {
                    path: '', // 空路径作为默认子路由
                    components: {
                        LeftPanel: () => import('@/views/main/component/MessageList.vue'),
                        RightPanel: () => import('@/views/main/component/Empty.vue')
                    }
                },
                {
                    path: 'chitchat',
                    components: {
                        LeftPanel: () => import('@/views/main/component/MessageList.vue'),
                        RightPanel: () => import('@/views/main/component/MessageDialog.vue')
                    },
                }, 
                {
                    path: 'groupchat',
                    components: {
                        LeftPanel: () => import('@/views/main/component/MessageList.vue'),
                        RightPanel: () => import('@/views/main/component/GroupChatDialog.vue')
                    }
                },
                {
                    path: 'friend',
                    components: {
                        LeftPanel: () => import('@/views/main/component/AddressList.vue'),
                        RightPanel: () => import('@/views/main/component/FriendRequest.vue')
                    }
                }
            ]
        },
        {
            path: '/videoCall',
            component: () => import('@/views/action/VideoCall.vue')
        }
    ]
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    // 放行公开路由：起始页、登录页、注册页
    if (to.path === '/' || to.path === '/in' || to.path === '/up') {
        next();
        return;
    }

    // 获取 token
    const token = localStorage.getItem('token');

    // 情况一：没有 token，未登录，跳转首页并提示
    if (!token) {
        message.warning('检测到您处于未登录状态，请先登录！');
        next('/');
        return;
    }

    // 情况二：有 token，需要验证其是否有效（调用后端接口）
    const { data: res } = await VerifyToken_API();

    if (res && res.data === true) {
        // Token 有效，允许访问目标路由
        next();
    } else {
        // Token 无效 / 过期，清除本地 token，跳转起始页并提示
        localStorage.removeItem('token');
        message.error('登录已过期，请重新登录！');
        next('/');
    }
});

export default router